package com.imooc.mvcdemo.controller;

import com.imooc.mvcdemo.model.Course;
import com.imooc.mvcdemo.service.CourseService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;

@Controller
@RequestMapping("/courses")
public class CourseController {
    private static Logger log = LoggerFactory.getLogger(CourseController.class);

    private CourseService courseService;

    @Autowired
    private HttpServletRequest request01;

    @Autowired
    public void setCourseService(CourseService courseService) {
        this.courseService = courseService;
    }

    //本方法将处理 /courses/view?courseId=123 形式的URL
    @RequestMapping(value = "/view", method = RequestMethod.GET)
    public String viewCourse(Integer courseId, Model model, HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");


        log.debug("In viewCourse, courseId = {}, request == request01 {}", courseId, request == request01);
        log.debug("In viewCourse, request01.courseId = {}", request01.getParameter("courseId"));
        log.debug("In viewCourse, request.courseId = {}", request.getParameter("courseId"));

        log.debug(ReflectionToStringBuilder.toString(request01));
        log.debug(ReflectionToStringBuilder.toString(request));
        log.debug(ReflectionToStringBuilder.toString(courseService));

        Course course = courseService.getCoursebyId(courseId);
        model.addAttribute(course);

        return "course_overview";
    }


    @RequestMapping(value = "/view2/{couseId}", method = RequestMethod.GET)
    public String viewCourse2(@PathVariable("couseId") Integer courseId, Map<String, Object> model) {
        log.debug("In viewCourse2, courseId={} request01.courseId = {}",
                courseId, request01.getParameter("courseId"));

        Course course = courseService.getCoursebyId(courseId);
        log.debug(ReflectionToStringBuilder.toString(course));


        model.put("course", course);
        return "course_overview";
    }

    @RequestMapping(value = "/view3", method = RequestMethod.GET)
    public String viewCourse3(HttpServletRequest request) {
        Integer courseId = Integer.valueOf(request.getParameter("courseId"));

        log.debug("In viewCourse3, courseId={} request01.courseId = {}",
                courseId, request01.getParameter("courseId"));

        Course course = courseService.getCoursebyId(courseId);
        log.debug(ReflectionToStringBuilder.toString(course));

        request.setAttribute("course", course);
        return "course_overview";
    }


    @RequestMapping(value = "/admin", method = RequestMethod.GET, params = "add")
    public String createCourse() {
        return "course_admin/edit";
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String doSave(@ModelAttribute Course course) {
        log.debug("Info of Course:");
        log.debug(ReflectionToStringBuilder.toString(course));
        //在此进行业务操作，比如数据库持久化
        course.setCourseId(136);
        return "redirect:view2/" + course.getCourseId();
    }


    @RequestMapping(value = "/upload", method = RequestMethod.GET)
    public String showUploadPage(@RequestParam(value = "multi", required = false) Boolean multi) {
        log.debug("showUploadPage, 文件上传 multi = {}", multi);
        if (multi != null && multi) {
            return "course_admin/multifile";
        }
        return "course_admin/file";
    }


    // 单文件上传
    @RequestMapping(value = "doUpload", method = RequestMethod.POST)
    public String doUpload(@RequestParam("file") MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            log.debug("Process file: {}", file.getOriginalFilename());
            log.debug("file = {}", ReflectionToStringBuilder.toString(file));
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File("c\\temp\\", System.currentTimeMillis() + file.getOriginalFilename()));
        }

        return "success";
    }

    // 多文件上传
    @RequestMapping(value = "doUpload2", method = RequestMethod.POST)
    public String doUpload2(MultipartHttpServletRequest multiRequest) throws IOException {
        Iterator<String> fileNames = multiRequest.getFileNames();
        log.debug("fileNames = {}", ReflectionToStringBuilder.toString(fileNames));

        while (fileNames.hasNext()) {
            String fileName = fileNames.next();
            MultipartFile file = multiRequest.getFile(fileName);
            if (!file.isEmpty()) {
                log.debug("Process file: {}", file.getOriginalFilename());
                FileUtils.copyInputStreamToFile(file.getInputStream(), new File("c:\\temp\\", System.currentTimeMillis() + file.getOriginalFilename()));
            }
        }

        return "success";
    }


    @RequestMapping(value = "/{courseId}", method = RequestMethod.GET)
    public Course getCourseInJson(@PathVariable("courseId") Integer courseId) {
        log.debug("In getCourseInJson, courseId={}", courseId);

        Course course = courseService.getCoursebyId(courseId);
        return course;
    }


    @RequestMapping(value = "json2/{courseId}", method = RequestMethod.GET)
    public @ResponseBody Course getCourseInJson2(@PathVariable("courseId") Integer courseId) {
        log.debug("In getCourseInJson2, courseId={}", courseId);

        Course course = courseService.getCoursebyId(courseId);
        return course;
    }

    @RequestMapping(value = "json3/{courseId}", method = RequestMethod.GET)
    public ResponseEntity<Course>  getCourseInJson3(@PathVariable("courseId") Integer courseId) {
        log.debug("In getCourseInJson3, courseId={}", courseId);

        Course course = courseService.getCoursebyId(courseId);
        return new ResponseEntity<Course>(course, HttpStatus.OK);
    }

}
